package com.hmall.common.interceptor;

import com.hmall.common.utils.UserContext;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * MQ用户信息拦截器，用于在消息消费前自动设置用户上下文
 */
public class MQUserInterceptor implements ChannelAwareMessageListener {
    
    private final ChannelAwareMessageListener target;
    
    public MQUserInterceptor(ChannelAwareMessageListener target) {
        this.target = target;
    }
    
    @Override
    public void onMessage(Message message, com.rabbitmq.client.Channel channel) throws Exception {
        try {
            // 从消息头中获取用户信息
            MessageProperties properties = message.getMessageProperties();
            if (properties != null) {
                Map<String, Object> headers = properties.getHeaders();
                if (headers != null && headers.containsKey("user-info")) {
                    Object userIdObj = headers.get("user-info");
                    if (userIdObj != null) {
                        try {
                            Long userId = Long.valueOf(userIdObj.toString());
                            UserContext.setUser(userId);
                        } catch (NumberFormatException e) {
                            // 忽略无效的用户ID
                        }
                    }
                }
            }
            
            // 执行实际的消息处理逻辑
            target.onMessage(message, channel);
        } finally {
            // 清理用户上下文
            UserContext.removeUser();
        }
    }
}